// 封装购物车模块

import { defineStore } from 'pinia'
import { ref,computed } from 'vue'
import {ElMessage} from "Element-Plus"


export  const useCartStore = defineStore('cart', () => {
    //购物车列表
    const cartList =ref<any>([])
  // 2. 定义action - addCart
  const addCartList =async (goods:any) => {
    const item = cartList.value.find((item:any) => goods.skuId === item.skuId)
    console.log(item);
    
    if (item) {
      // 找到了
      item.count++
      ElMessage.success('加入购物车成功')
    } else {
      // 没找到
      cartList.value.push(goods)
      ElMessage.success('加入购物车成功')

    }
    
   
  }
    // 删除购物车
    const delCart = async (skuId:any) => {
      
         // 思路：
      // 1. 找到要删除项的下标值 - splice
      // 2. 使用数组的过滤方法 - filter
      const idx = cartList.value.findIndex((item:any) => skuId === item.skuId)
      cartList.value.splice(idx, 1);
      
     
  }
  //退出登录
  const clearCart=()=>{
    cartList.value=[]
    
  }
    // 计算属性
  // 1. 总的数量 所有项的count之和
  const allCount = computed(() => cartList.value.reduce((a:any, c:any) => a + c.count, 0))
  // 2. 总价 所有项的count*price之和
  const allPrice = computed(() => cartList.value.reduce((a:any, c:any) => a + c.count * c.price, 0))
  //单选功能
  const getsingleCheck=(skuId:any,selected:any)=>{
    const item = cartList.value.find((item:any) => item.skuId === skuId)
  item.selected = selected
  }
  // 全选功能action
const allCheck = (selected:any) => {
  // 把cartList中的每一项的selected都设置为当前的全选框状态
  cartList.value.forEach((item:any) => item.selected = selected)
}
// 是否全选计算属性
const isAll = computed(() => cartList.value.every((item:any) => item.selected))
// 3. 已选择数量
const selectedCount = computed(() => cartList.value.filter((item:any )=> item.selected).reduce((a:any, c:any) => a + c.count, 0))
// 4. 已选择商品价钱合计
const selectedPrice = computed(() => cartList.value.filter((item:any) => item.selected).reduce((a:any, c:any) => a + c.count * c.price, 0))
  return {
    cartList,
    addCartList,
    delCart,
    allCount,
    allPrice,
    getsingleCheck,
    allCheck,
    isAll,
    selectedCount,
    selectedPrice,
    clearCart
  }
}, {
  persist: true,
})

